﻿using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

namespace TextCompare
{
    class TextBlockFormatter : IFormatter
    {
        private Paragraph paragraph;

        public TextBlockFormatter(RichTextBox textBlock)
        {
            textBlock.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
            textBlock.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
            textBlock.IsReadOnly = true;

            FlowDocument doc = new FlowDocument();
            paragraph = new Paragraph();
            doc.Blocks.Add(paragraph);
            textBlock.Document = doc;
        }

        public void Write(ITextMatcher textMatcher, IEnumerable<MatchPoint> points)
        {
            if (textMatcher.SourceCount == 0 || textMatcher.TargetCount == 0 || points == null)
                return;

            if (points.Count() == 0)
            {
                WriteAll(textMatcher.Source, textMatcher.Target);
                return;
            }

            WriteByPoint(textMatcher, points);
        }

        private void WriteAll(string source, string target)
        {
            paragraph.Inlines.Add(new Run(target) { Foreground = new SolidColorBrush(Colors.Red), TextDecorations = TextDecorations.Strikethrough });
            paragraph.Inlines.Add(new Run(source) { Background = new SolidColorBrush(Colors.LimeGreen) });
        }

        private void WriteByPoint(ITextMatcher textMatcher, IEnumerable<MatchPoint> points)
        {
            foreach (var point in points)
            {
                switch (point.Direction)
                {
                    case Direction.DownRight:
                        paragraph.Inlines.Add(new Run(textMatcher.GetSourceSubString(point.X,point.Y)));
                        break;
                    case Direction.Down:
                        paragraph.Inlines.Add(new Run(textMatcher.GetSourceSubString(point.X,point.Y)) { Background = new SolidColorBrush(Colors.LimeGreen) });
                        break;
                    case Direction.Right:
                        paragraph.Inlines.Add(new Run(textMatcher.GetTargetSubString(point.X,point.Y))
                        {
                            Foreground = new SolidColorBrush(Colors.Red),
                            TextDecorations = TextDecorations.Strikethrough
                        });
                        break;
                    default:
                        break;
                }
            }
        }
    }
}
